package com.edu.controller;

import com.edu.bean.Book;
import com.edu.mapper.BookMapper;
import com.edu.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Controller
public class BookController {

    @Resource
    private BookService bookService;

    @RequestMapping("/getBooks")
    public Object getAllBooks(Model model){
        model.addAttribute("books", bookService.getAllBook());
        return "showBook.jsp";
    }

    @RequestMapping("/jumpBook")
    public Object jumpBook(Model model){
        Book book = new Book();
        model.addAttribute("book",book);
        return "addBook.jsp";
    }

    @RequestMapping("/addBook")
    public Object addBook(@Valid Book book, BindingResult bindingResult,Model model){
        if (bindingResult.hasErrors()) {
            return "addBook.jsp";
        }
        int row = bookService.addBook(book);
        if (row == 1) {
            return "redirect:/getBooks";
        } else if (row == -1){
            model.addAttribute("msg","书名存在");
        } else {
            model.addAttribute("msg","添加未成功");
        }
        return "addBook.jsp";
    }

    @RequestMapping("/getSomeBooks")
    @ResponseBody
    public List<Book> getBooks(@RequestBody Book book){
        return bookService.getBooks(book);
    }

    @RequestMapping("/addBook.ajax")
    @ResponseBody
    public Object addSomeBook(@RequestBody Book book){
        int i = bookService.addBook(book);
        return bookService.getBooks(new Book());
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(@RequestBody Book book){
        bookService.delBookById(book.getBookId());
        return bookService.getBooks(new Book());
    }

    @RequestMapping("/update")
    @ResponseBody
    public Object update(@RequestBody Book book){
        bookService.updateBookById(book);
        return bookService.getBooks(new Book());
    }

}
